package com.bacon.gmall.cart.controller;

import com.bacon.gmall.cart.service.CartService;
import com.bacon.gmall.common.result.Result;
import com.bacon.gmall.common.util.AuthContextHolder;
import com.bacon.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2021-01-04 11:04
 * @description:
 */
@RestController
@RequestMapping("/api/cart")
public class CartApiController {


    @Autowired
    private CartService cartService;

    @GetMapping("/addToCart/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable Long skuId,
                            @PathVariable Integer skuNum,
                            HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }

        cartService.addToCart(skuId, skuNum, userId);
        return Result.ok();
    }

    @GetMapping("findCartInfoBySkuId/{skuId}")
    public CartInfo findCartInfoBySkuId(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
        return cartService.findCartInfoBySkuId(skuId, userId);
    }

    //购物车结算
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) throws InterruptedException {
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);

        //如果两个都存在，需要进行合并
        List<CartInfo> cartInfoList = cartService.cartList(userId, userTempId);
        return Result.ok(cartInfoList);
    }

    /* url: this.api_name + '/checkCart/' + skuId + '/' + isChecked,*/
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,
                            @PathVariable Integer isChecked) {

        cartService.checkCart(skuId, isChecked);
        return Result.ok();
    }

    //对选中的商品下订单
    @GetMapping("/findCartListByIsChecked")
    public List<CartInfo> findCartListByIsChecked(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return cartService.findCartListByIsChecked(userId);
    }
}
